import {RouteObject} from 'react-router-dom'
import Trie from './trie.ts'

export function matchRoute(path: string, matchRoutes: RouteObject[]) {
  const [_path, searchStr] = path.split('?')
  path = _path
  const search = new URLSearchParams(searchStr)
  const trie = new Trie<RouteObject[]>()

  function flatAndInsert(
    subRoutes: RouteObject[],
    basePath = '',
    baseRoutes: RouteObject[] = [],
  ) {
    for (const route of subRoutes) {
      const { children, path: routePath } = route
      const fullPath = routePath?.startsWith('/')
        ? `${routePath}`
        : `/${routePath}`
      const nextPath = basePath + (fullPath === '/' ? '' : fullPath)
      const resultRoutes = [...baseRoutes, route]
      if (children) {
        flatAndInsert(children, nextPath, resultRoutes)
      } else {
        trie.insert(nextPath, resultRoutes)
      }
    }
  }
  flatAndInsert(matchRoutes)

  return [...trie.search(path), search] as const
}
